import React, { useState, useEffect } from 'react';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { LocalizationProvider, DatePicker } from '@mui/x-date-pickers';
import dayjs from 'dayjs';

import {
    Box,
    Button,
    Card,
    CardContent,
    TextField,
    IconButton,
    Select,
    MenuItem,
    Autocomplete,
    CircularProgress
} from '@mui/material';
import ClearIcon from '@mui/icons-material/Clear';

import { StudentSearchParams } from '../../../api/types';
import { SearchFormProps } from '../type';
import {
    fuzzySearchMajor,
    getAdvisorOptions,
    getEnrollmentStatusOptions,
    getEnrollmentTypeOptions
} from '../../../api/student';

// 提取搜索字段配置为常量
const getSearchFields =  (
    enrollmentStatusOptions: any,
    enrollmentTypeOptions: any,
    advisorOptions: any
) => [
    // { id: 'record_id', label: '记录ID', placeholder: '请输入记录ID' },
    // { id: 'seq', label: '序号', placeholder: '请输入序号' },
    { id: 'sid', label: '学号', type: 'text', placeholder: '请输入学号' },
    { id: 'name', label: '姓名', type: 'text', placeholder: '请输入姓名' },
    // { id: 'college', label: '书院', placeholder: '请选择书院' },
    { id: 'major', label: '专业', type: 'text', placeholder: '请输入专业' },
    // { id: 'grade', label: '年级', placeholder: '请选择年级' },
    // { id: 'phone', label: '联系方式', placeholder: '请输入手机号' },
    // { id: 'email', label: '邮箱', placeholder: '请输入邮箱' },
    {
        id: 'state',
        label: '学籍状态',
        type: 'select',
        placeholder: '请选择学籍状态',
        options:
            enrollmentStatusOptions.length > 0
                ? enrollmentStatusOptions.map((status) => ({ value: status, label: status }))
                : [
                    { value: '课程中有效', label: '课程中有效' },
                    { value: '休假', label: '休假' }
                ]
    },
    {
        id: 'approach',
        label: '招生类型',
        type: 'select',
        placeholder: '请选择招生类型',
        options:
            enrollmentTypeOptions.length > 0
                ? enrollmentTypeOptions.map((type) => ({ value: type, label: type }))
                : [
                    { value: '高考学生（中国籍）', label: '高考学生（中国籍）' },
                    { value: '海本学生（中国籍）', label: '海本学生（中国籍）' },
                    { value: '国际生', label: '国际生' }
                ]
    },
    {
        id: 'difficulty',
        label: '特需生',
        type: 'select',
        placeholder: '请选择是否为特需生',
        options: [
            { value: '是', label: '是' },
            { value: '否', label: '否' }
        ]
    },
    {
        id: 'partner',
        label: '顾问',
        type: 'select',
        placeholder: '请选择顾问',
        options:
            advisorOptions.length > 0
                ? advisorOptions.map((advisor) => ({ value: advisor, label: advisor }))
                : [
                    { value: 'Maxine', label: 'Maxine' },
                    { value: 'Laila', label: 'Laila' },
                    { value: 'Zoey', label: 'Zoey' },
                    { value: 'Bella', label: 'Bella' },
                    { value: 'Mandy', label: 'Mandy' },
                    { value: 'Sherry', label: 'Sherry' },
                    { value: 'Ann', label: 'Ann' },
                    { value: 'Ashley', label: 'Ashley' }
                ]
    }
    // { id: 'cgpa', label: '绩点', placeholder: '请输入绩点' }
];

const SearchForm: React.FC<SearchFormProps> = ({ initialSearchParams, enrollmentStatusOptions, enrollmentTypeOptions, advisorOptions, onSearch }) => {
    // 本地搜索状态
    const [localSearchValues, setLocalSearchValues] = useState<Record<string, string>>({});

    // 专业模糊搜索相关状态
    const [majorOptions, setMajorOptions] = useState<string[]>([]);
    const [majorSearchInput, setMajorSearchInput] = useState('');
    const [majorSearchLoading, setMajorSearchLoading] = useState(false);

    // 初始化本地状态
    useEffect(() => {
        // 提取字符串类型的字段到本地状态
        const initialLocalValues: Record<string, string> = {};
        Object.entries(initialSearchParams).forEach(([key, value]) => {
            if (typeof value === 'string') {
                initialLocalValues[key] = value;
            }
        });
        setLocalSearchValues(initialLocalValues);
    }, [initialSearchParams]);

    // 处理搜索参数变化
    const handleSearchChange = (field: string, value: string) => {
        setLocalSearchValues((prev) => ({
            ...prev,
            [field]: value
        }));
    };

    // 统一处理日期变化的函数
    const handleDateFieldChange = (field: string, date: dayjs.Dayjs | null, format: string = 'YYYY-MM-DD') => {
        setLocalSearchValues((prev) => ({
            ...prev,
            [field]: date ? date.format(format) : ''
        }));
    };

    // 清除日期字段
    const clearDateField = (field: string) => {
        setLocalSearchValues((prev) => ({
            ...prev,
            [field]: ''
        }));
    };

    // 处理专业搜索
    const handleMajorSearch = async (value: string) => {
        setMajorSearchInput(value);

        if (value.trim().length < 1) {
            setMajorOptions([]);
            return;
        }

        setMajorSearchLoading(true);
        try {
            const results = await fuzzySearchMajor(value);
            setMajorOptions(results);
        } catch (error) {
            console.error('搜索专业失败:', error);
            setMajorOptions([]); // 确保错误时也设置空数组
        } finally {
            setMajorSearchLoading(false);
        }
    };

    // 处理专业选择
    const handleMajorSelect = (_: React.SyntheticEvent, value: string | null) => {
        setLocalSearchValues((prev) => ({
            ...prev,
            major: value || ''
        }));

        // 清空搜索输入值，使下拉框关闭
        setMajorSearchInput('');
    };

    // 生成唯一键值
    let optionKeyCounter = 0;
    const getOptionKey = (option: string) => {
        optionKeyCounter++;
        return `${option}-${optionKeyCounter}`;
    };

    // 处理查询
    const handleSearch = () => {
        // 创建更新后的参数对象
        const updatedParams: StudentSearchParams = {
            ...initialSearchParams,
            ...localSearchValues,
            graduation_pre: dayjs(localSearchValues.graduation_pre).unix(),
            graduation_year: dayjs(localSearchValues.graduation_year).unix(),
            page: 1
        };

        // 调用父组件的搜索函数
        onSearch(updatedParams);
    };

    return (
        <Card variant="outlined" sx={{ mb: 3 }} className="search-form">
            <CardContent>
                <Box
                    sx={{
                        display: 'grid',
                        gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',
                        gap: 2
                    }}>
                    {getSearchFields(enrollmentStatusOptions, enrollmentTypeOptions, advisorOptions).map((field) => (
                        <Box
                            key={field.id}
                            sx={{
                                display: 'flex',
                                alignItems: 'center'
                            }}>
                            <Box sx={{ flexShrink: 0, width: '100px', textAlign: 'right', pr: 1 }}>{field.label}:</Box>
                            {field.type === 'select' ? (
                                <Select
                                    size="small"
                                    fullWidth
                                    value={localSearchValues[field.id] || ''}
                                    onChange={(e) => handleSearchChange(field.id, e.target.value as string)}
                                    variant="outlined">
                                    {field.options?.map((option) => (
                                        <MenuItem key={option.value} value={option.value}>
                                            {option.label}
                                        </MenuItem>
                                    ))}
                                </Select>
                            ) : field.id === 'major' ? (
                                <Autocomplete
                                    sx={{ width: '100%' }}
                                    id="major-search"
                                    freeSolo
                                    options={majorOptions}
                                    value={localSearchValues.major || ''}
                                    inputValue={majorSearchInput}
                                    getOptionKey={getOptionKey}
                                    onInputChange={(_, newInputValue) => {
                                        handleMajorSearch(newInputValue);
                                    }}
                                    onChange={handleMajorSelect}
                                    loading={majorSearchLoading}
                                    loadingText="搜索中..."
                                    renderInput={(params) => (
                                        <TextField
                                            {...params}
                                            size="small"
                                            fullWidth
                                            variant="outlined"
                                            InputProps={{
                                                ...params.InputProps,
                                                endAdornment: (
                                                    <React.Fragment>
                                                        {majorSearchLoading ? (
                                                            <CircularProgress color="inherit" size={20} />
                                                        ) : null}
                                                        {params.InputProps.endAdornment}
                                                    </React.Fragment>
                                                )
                                            }}
                                        />
                                    )}
                                />
                            ) : (
                                <TextField
                                    size="small"
                                    fullWidth
                                    value={localSearchValues[field.id] || ''}
                                    onChange={(e) => handleSearchChange(field.id, e.target.value)}
                                    variant="outlined"
                                />
                            )}
                        </Box>
                    ))}

                    {/* 毕业年份选择器 */}
                    <Box
                        sx={{
                            display: 'flex',
                            alignItems: 'center'
                        }}>
                        <Box sx={{ flexShrink: 0, width: '100px', textAlign: 'right', pr: 1 }}>毕业年份:</Box>
                        <Box sx={{ position: 'relative', width: '100%' }}>
                            <LocalizationProvider dateAdapter={AdapterDayjs}>
                                <DatePicker
                                    views={['year']}
                                    format="YYYY"
                                    value={
                                        localSearchValues.graduation_year
                                            ? dayjs(localSearchValues.graduation_year)
                                            : null
                                    }
                                    onChange={(date) => handleDateFieldChange('graduation_year', date, '')}
                                    slotProps={{
                                        textField: {
                                            size: 'small',
                                            fullWidth: true,
                                            // placeholder: '选择毕业年份',
                                            variant: 'outlined'
                                        }
                                    }}
                                />
                            </LocalizationProvider>
                            {localSearchValues.graduation_year && (
                                <IconButton
                                    size="small"
                                    sx={{
                                        position: 'absolute',
                                        right: '40px',
                                        top: '50%',
                                        transform: 'translateY(-50%)'
                                    }}
                                    onClick={() => clearDateField('graduation_year')}>
                                    <ClearIcon fontSize="small" />
                                </IconButton>
                            )}
                        </Box>
                    </Box>
                </Box>
                <Box sx={{ display: 'flex', justifyContent: 'center', mt: 3 }}>
                    <Button variant="contained" onClick={handleSearch} sx={{ minWidth: 120 }}>
                        查询
                    </Button>
                </Box>
            </CardContent>
        </Card>
    );
};

export default SearchForm;
